import {
  PipeTransform,
  Injectable,
  ArgumentMetadata,
  BadRequestException,
} from '@nestjs/common';

@Injectable()
export class ParseIntPipe implements PipeTransform<string, number> {
  transform(value: string): number {
    if (value === undefined || value === null || value === '') {
      throw new BadRequestException('Value is required');
    }

    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Value must be a valid integer');
    }
    return val;
  }
}

@Injectable()
export class ParseOptionalIntPipe
  implements PipeTransform<string, number | undefined>
{
  constructor(private readonly defaultValue?: number) {}

  transform(value: string, metadata: ArgumentMetadata): number | undefined {
    if (value === undefined || value === null || value === '') {
      return this.defaultValue;
    }

    const val = parseInt(value, 10);
    if (isNaN(val)) {
      if (this.defaultValue !== undefined) {
        return this.defaultValue;
      }
      throw new BadRequestException(`参数 "${metadata.data}" 必须是有效的整数`);
    }
    return val;
  }
}
